﻿using System.Collections.Generic;
using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Domain.Wrappers;

namespace Cms.Application.Admin.Presenters
{
    public class PluginsPresenter : BasePresenter
    {
        private readonly IPluginsView _view;
        private readonly Administrator _administrator;

        public PluginsPresenter(IPluginsView view)
            : this(view, new RepositoryFactory())
        {
        }

        public PluginsPresenter(IPluginsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Plugins)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetPlugins();
        }

        public void SetPlugins()
        {
            PluginHandler.SyncPlugins(SystemRepository);

            IList<PluginDescription> pluginDescriptions = new List<PluginDescription>();
            IList<Plugin> plugins = SystemRepository.GetPlugins();
            foreach (Plugin p in plugins)
            {
                string translationFile = "Admin/Translations/Plugins/" + p.GetClassName() + ".xml";
                string name = Translator.GetText(translationFile, "PluginName", _view.Localization);
                string description = Translator.GetText(translationFile, "PluginDescription", _view.Localization);
                pluginDescriptions.Add(new PluginDescription(name,
                                                             description,
                                                             p.GetType().Name == "TemplatablePlugin",
                                                             p));
            }
            _view.SetPlugins(pluginDescriptions);
        }

        public IList<PluginTemplate> GetTemplates(TemplatablePlugin plugin)
        {
            return plugin.GetTemplates(_administrator.CurrentSite.ID);
        }
    }
}